var express = require('express');
var router = express.Router();
const {getList, getDetail, newBlog, updateBlog, delBlog} = require('../controller/blog.js');
const {SuccessModel, ErrorModel} = require('../model/resModel.js');
const loginCheck = require('../middleware/loginCheck.js');
router.get('/list', (req, res, next) =>{
  let author = req.query.author || ''
  let keyword = req.query.keyword || ''
  if (req.query.isadmin) {
    if (req.session.username == null) {
      res.json(new ErrorModel('登入失败'))
    }
    author = req.session.realname
  }
  const result = getList(author, keyword) //返回promise
  return result.then(listdata => {
    res.json(new SuccessModel(listdata))
  })
});
router.get('/detail',(req,res,next)=>{
  
  const result = getDetail(req.query.id)
  return result.then(data=>{
    res.json(
      new SuccessModel(data)
    )
  })
});
router.post('/new',loginCheck,(req,res,next)=>{
  req.body.author=req.session.realname
  const result = newBlog(req.body)
  return result.then(data=>{
    if (data){
      res.json(new SuccessModel('更新成功'))
    } else {
      es.json( new ErrorModel('更新失败'))
    }
  })
})
router.post('/update',loginCheck,(req,res,next)=>{
  
  const result = updateBlog(req.query.id,req.body)
  return result.then(value => {
    if (value) {
      res.json(new SuccessModel('更新成功') )
    } else {
      res.json(new ErrorModel('更新博客失败'))
    }
  })
})
router.post('/del',loginCheck,(req,res,next)=>{
  const result = delBlog(req.query.id,req.session.realname)
  return result.then(value => {
    if (value) {
      res.json(new SuccessModel('删除成功'))
    } else {
      res.json(new ErrorModel('删除失败'))
    }
  })
})
module.exports = router;
